package chapters15_bingfa.chapters15_2;

/**
 * Created by xinxuchu on 2020/1/26.
 */
public class CounterThread extends Thread {

    Counter counter;

    StaticCounter staticCounter;

    public CounterThread(Counter counter) {
        this.counter = counter;
    }

    public CounterThread(StaticCounter staticCounter) {
        this.staticCounter = staticCounter;
    }

    @Override
    public void run(){
        if (counter !=null){
            for (int i = 0; i < 1000; i++) {
                counter.incr();
            }
        }
        if (staticCounter!=null){
            for (int i = 0; i < 1000; i++) {
                staticCounter.incr();
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        int num = 1000;
        Counter counter = new Counter();//这里新建一个实例对象，synchronized关键字搞定的是实例对象
        Thread[] threads = new Thread[num];
        for (int i = 0; i <num ; i++) {
            threads[i] = new CounterThread(counter);
            threads[i].start();
        }

        for (int i = 0; i < num ; i++) {
            threads[i].join();
        }

        System.out.println(counter.getCount());

        Counter counter1 = new Counter();
        Counter counter2 = new Counter();
        Thread thread1 = new CounterThread(counter1);
        Thread thread2 = new CounterThread(counter2);
        thread1.start();

        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(counter1.getCount());
        System.out.println(counter2.getCount());
        System.out.println("####################################3");

        //静态方法测试
        //synchronized修饰静态类的时候，确实和对象无关，而和静态类有关
        //这可真他么帅气，只要调用的是这个静态类，不管谁都会改变这个参数
        StaticCounter staticCounter1 = new StaticCounter();
        StaticCounter staticCounter2 = new StaticCounter();
        Thread thread3 = new CounterThread(staticCounter1);
        Thread thread4 = new CounterThread(staticCounter2);

        thread3.start();
        thread4.start();
        System.out.println(staticCounter1.getCount());
        thread3.join();

        thread4.join();

        System.out.println(staticCounter1.getCount());


    }
}
